package org.ediba.siri.web.rest;

import java.beans.PropertyEditorSupport;
import java.util.LinkedList;
import java.util.List;

import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

public class IntArrayPropertyEditor extends PropertyEditorSupport {
	
	/**
	 * Default separator for splitting a String: a comma (",")
	 */
	public static final String DEFAULT_SEPARATOR = ",";
	
	private final String separator;
	private final boolean emptyArrayAsNull;
	private final boolean ignoreEmptyValues;
	
	public IntArrayPropertyEditor() {
		this(DEFAULT_SEPARATOR, false, false);
	}
	
	public IntArrayPropertyEditor(String separator, boolean emptyArrayAsNull, boolean ignoreEmptyValues) {
		this.separator = separator;
		this.emptyArrayAsNull = emptyArrayAsNull;
		this.ignoreEmptyValues = ignoreEmptyValues;
	}
	
	@Override
	public void setAsText(String text) throws IllegalArgumentException {

		String[] array = StringUtils.delimitedListToStringArray(text, this.separator);
		List<Integer> list = new LinkedList<Integer>();

		for (String string : array) 
			if (StringUtils.hasText(string))
				try {list.add(Integer.parseInt(string));}
				catch (NumberFormatException e) {throw new IllegalArgumentException();}
			else 
				if (!this.ignoreEmptyValues)
					list.add(null);
			
		if (this.emptyArrayAsNull && array.length == 0)
			this.setValue(null);
		else 
			this.setValue(list.toArray());
	
	}

	@Override
	public String getAsText() {
		return StringUtils.arrayToDelimitedString(ObjectUtils.toObjectArray(getValue()), this.separator);
	}

}
